package com.zbkj.admin.config;

import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.client.web.DefaultOAuth2AuthorizationRequestResolver;
import org.springframework.security.oauth2.client.web.OAuth2AuthorizationRequestResolver;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;

import java.net.URI;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@Slf4j
public class WechatOAuth2AuthorizationRequestResolver implements OAuth2AuthorizationRequestResolver {

    private final OAuth2AuthorizationRequestResolver defaultResolver;

    public WechatOAuth2AuthorizationRequestResolver(ClientRegistrationRepository repo) {
        this.defaultResolver = new DefaultOAuth2AuthorizationRequestResolver(repo, "/oauth2/authorization");
    }

    @Override
    public OAuth2AuthorizationRequest resolve(HttpServletRequest request) {
        // 构建标准请求
        OAuth2AuthorizationRequest req = defaultResolver.resolve(request);
        if (req == null) {
            return null;
        }
        log.info("微信授权请求：{}", req.getClientId());
        // 适配微信参数：替换client_id为appid，并添加#wechat_redirect后缀
        return OAuth2AuthorizationRequest.from(req)
                .clientId(req.getClientId())
                .authorizationRequestUri(uriBuilder -> {
                    String text = uriBuilder
                            .replaceQueryParam("client_id", (Object) null) // 关键：移除client_id
                            .replaceQueryParam("state", (Object) null) // 关键：移除client_id
                            .replaceQueryParam("appid", req.getClientId())
                            .replaceQueryParam("redirect_uri", URLEncoder.encode(req.getRedirectUri(), StandardCharsets.UTF_8))
                            .replaceQueryParam("response_type", "code")
                            .replaceQueryParam("scope", String.join(",", req.getScopes()))
                            .replaceQueryParam("state", req.getState())
                            .build() + "#wechat_redirect";
                    URI uri = URI.create(text.replaceAll("client_id&state&", ""));
                    log.info("微信授权请求地址：{}", uri);
                    return uri;
                })
                .build();
    }

    /**
     * Returns the {@link OAuth2AuthorizationRequest} resolved from the provided
     * {@code HttpServletRequest} or {@code null} if not available.
     *
     * @param request              the {@code HttpServletRequest}
     * @param clientRegistrationId the clientRegistrationId to use
     * @return the resolved {@link OAuth2AuthorizationRequest} or {@code null} if not
     * available
     */
    @Override
    public OAuth2AuthorizationRequest resolve(HttpServletRequest request, String clientRegistrationId) {
        return null;
    }
}